// 和广告操作有关的路由；
const express = require("express");
const fs = require("fs");
const advRouter = express.Router();
const {uploadfile} = require("../util");
const advModel = require("../models/advModel");

let perpage = 3; // 每页显示的条数

advRouter.get("/test",(req,res)=>{
    res.json({
        info:"测试文件",
        status:1
    })
})

advRouter.post("/add",async (req,res)=>{
    try {
        let obj = await uploadfile(req);
        obj.time = new Date().toLocaleDateString();
        await advModel.create(obj);
        let data = await advModel.find();
        res.json({
            info: "添加成功",
            status: 1,
            p:Math.ceil(data.length/perpage)
        })
    }catch(err){
        res.json({
            info:"添加失败",
            status:0
        })
    }

})

advRouter.get("/get",async (req,res)=>{
    
    let {p = 1} = req.query;  // 当前页面，默认在第一页 
    // console.log("当前",p);
    let data = await advModel.find();
    let pageCount = Math.ceil(data.length/perpage);
    let advs = await advModel.find().skip((p-1)*perpage).limit(perpage);
    res.json({advs,pageCount});  // 通过ajax返还给前端；
})



advRouter.delete("/del",async (req,res)=>{
    let {_id,img} = req.query;
    try{
        // console.log(img);
        let delurl = process.cwd()+"/static/"+img;
        if(fs.existsSync(delurl)){  // 判断 文件是否存在 ，如果存在就删除；
            fs.unlinkSync(delurl);
        }
        await advModel.deleteOne({_id});
        res.json({
            info:"删除成功",
            status:1
        })
    }catch(err){
        console.log(err);
        res.json({
            info:"删除失败",
            status:0,
            err
        })
    }
})



advRouter.put("/update",async (req,res)=>{
    try {
        let obj = await uploadfile(req);
        let [{img}] = await advModel.find({_id:obj._id})
        let delurl = process.cwd()+"/static/"+img;

        if(fs.existsSync(delurl)){  // 判断 文件是否存在 ，如果存在就删除；
            fs.unlinkSync(delurl);
        }
        obj.time = new Date().toLocaleDateString();
        
        await advModel.updateOne({_id:obj._id},{$set:obj});
        res.json({
            info: "添加成功",
            status: 1
        })
    }catch(err){
        res.json({
            info:"添加失败",
            status:0
        })
    }
})


module.exports = advRouter;